package com.github.mq;

import io.lettuce.core.StreamMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RedisStreamService {

    @Value("${spring.redis.stream-name}")
    private String streamKey;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送消息到Stream（字符串格式）
     */
    public void sendMessage(String sessionId,String deviceType,String message) {
        try {
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("sessionId", sessionId);
            messageMap.put("deviceType",deviceType);
            messageMap.put("message" ,message);
            MapRecord<String, String, String> record = StreamRecords.newRecord()
                    .ofStrings(messageMap)
                    .withStreamKey(streamKey);
            stringRedisTemplate.opsForStream().add(record);
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败: " + e.getMessage(), e);
        }
    }
    /**
     * 发送消息到Stream（字符串格式）
     */
    public void sendAccountMessage(String account,String deviceType,String message) {
        try {
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("account", account);
            messageMap.put("deviceType",deviceType);
            messageMap.put("message" ,message);
            MapRecord<String, String, String> record = StreamRecords.newRecord()
                    .ofStrings(messageMap)
                    .withStreamKey(streamKey);
            stringRedisTemplate.opsForStream().add(record);
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败: " + e.getMessage(), e);
        }
    }


    /**
     * 获取Stream长度
     */
    public Long getStreamLength() {
        try {
            return stringRedisTemplate.opsForStream().size(streamKey);
        } catch (Exception e) {
            System.err.println("获取Stream长度失败: " + e.getMessage());
            return 0L;
        }
    }

//    /**
//     * 获取消费者组信息
//     */
//    public List<Object> getConsumerGroups() {
//        try {
//            return stringRedisTemplate.opsForStream().groups(streamKey);
//        } catch (Exception e) {
//            System.err.println("获取消费者组信息失败: " + e.getMessage());
//            return Collections.emptyList();
//        }
//    }
}